import ScrollBarLayout from '@/components/ScrollBarLayout';
import Cls from 'classnames';
import { useContext, useEffect, useState } from 'react';
import { ChangeControllerContext } from '../common/useOAContext';
import { Form, Select, Spin, Tooltip, TreeSelect, message, Button } from 'antd';
import { useDescriptions, Descriptions } from '@/components/Descriptions';
import { downloadTemplate, getFileNameNotType, getLoadMapList, getTenantID, removeDateHmsStr, splitFileUrl } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import MyIcon from '@/components/MyIcon';
import { formatDecimal } from '../../Acommon';
import { handleNotPostion } from '@/pages/ContractController/ContractManage/mconfig';
import { getFlowOrgTreeByOrgIDService, getUserDataList } from '@/services/BaseLayout';
import UpdatePackList from './UpdatePackList';
import UpdateContractList from './UpdateContractList';
import { TypographyTitle } from '@/components/Typography/TypographyTitle';
import { getBaseUrl } from '@/services/urlconst';
import { readReadShowFileService } from '@/services/BaseLayout';
import { EyeOutlined } from '@ant-design/icons';

export const DetailInfoCenterViewMainOA: React.FC = () => {
  /** 引入上下文 */
  const { styleFixCls, infoObj } = useContext(ChangeControllerContext);

  /**  获取数据字典 */
  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_TYPE}`, //资产类型
    `${getTenantID()}${ILoadMapTypeAll.AVERAGE_LIFE_METHOD}`, //折旧方式
    `${getTenantID()}${ILoadMapTypeAll.ASSET_SOURCE_TYPE}`, //资产来源
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_BRAND}`, //资产品牌
    `${getTenantID()}${ILoadMapTypeAll.ASSET_AREA}`, //资产存放区域
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`, //计量单位
  ]);

  const [changeFromRef] = Form.useForm(); // 表单实例

  /** 获取组织机构树接口 */
  const { getFlowOrgTreeRun, getFlowOrgTreeLoading, getFlowOrgList } = getFlowOrgTreeByOrgIDService();

  /** 获取当前部门用户数据 */
  const { getUserRun, getUserLoading, getUserList } = getUserDataList((res: any) => {
    if (!(res && res?.msgFlag)) {
      message.error(res?.msg);
    }
  });

  /** 轻阅读预览 */
  const { readReadShowFileRun } = readReadShowFileService();

  /**轻阅读预览 */
  const onOpenReadOfdWord = (fieldUrl: string) => {
    readReadShowFileRun({ fieldPath: `${getBaseUrl()}${fieldUrl}` });
  };

  useEffect(() => {
    /** 初始化请求组织机构 */
    let payload = {
      params: '0',
      flowType: '0',
    };
    getFlowOrgTreeRun(payload);
    if (infoObj?.id) {
      getUserRun({
        //获取当前部门用户信息
        userDepartmentID: infoObj?.useDepartmentID,
      });
      BasicMethods?.setFieldsValue({
        ...infoObj,
        expectSum: formatDecimal(infoObj?.expectSum),
      });
      ReMethods?.setFieldsValue({
        ...infoObj,
        expectSum: formatDecimal(infoObj?.expectSum),
      });
    }
  }, [infoObj]);

  // 表格表单配置信息
  const [config, BasicMethods] = useDescriptions({
    labelWidth: 200,
    basicForm: changeFromRef,
    schemas: [
      {
        field: `createTime`,
        label: `申请日期`,
        component: 'Render',
        disabled: true,
        placeholder: '自动带出',
        render: (text: string) => <span>{removeDateHmsStr(text)}</span>,
      },
      {
        field: `applyCode`,
        label: `流水单号`,
        component: 'Input',
        disabled: true,
        placeholder: '自动带出',
      },
      {
        field: `createrName`,
        label: `申请人`,
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
      },
      {
        field: `createPhone`,
        label: `联系电话`,
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
      },
      {
        field: `createDepartmentName`,
        label: `申请部门`,
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
      },
      {
        field: `createPositionName`,
        label: `职务岗位`,
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
      },
    ],
  });

  // 表格表单配置信息
  const [ReConfig, ReMethods] = useDescriptions({
    labelWidth: 200,
    basicForm: changeFromRef,
    schemas: [
      {
        field: `applyTitle`,
        label: `事项名称`,
        component: 'Input',
        disabled: true,
        placeholder: '请输入',
        colSpan: 0,
      },
      {
        field: `assetName`,
        label: `资产名称`,
        component: 'Input',
        disabled: true,
      },
      {
        field: `usedTypeName`,
        label: `资产用途`,
        component: 'Render',
        disabled: true,
        placeholder: '自动带出',
        render: (text) => {
          return <span>{text ? text.split('||')[0] : '--'}</span>;
        },
      },
      {
        field: `assetClassName`,
        label: `资产分类`,
        component: 'Render',
        disabled: true,
        placeholder: '自动带出',
        render: (text) => {
          return <span>{text ? text.split('||')[0] : '--'}</span>;
        },
      },
      {
        field: `assetClassCode`,
        label: `资产分类编码`,
        component: 'Input',
        disabled: true,
        placeholder: '自动带出',
      },
      // {
      //   field: `sourceTypeName`,
      //   label: `资产来源`,
      //   component: 'Render',
      //   disabled: true,
      //   placeholder: '自动带出',
      //   render: (text) => {
      //     return <span>{text ? text.split('||')[0] : '--'}</span>;
      //   },
      // },
      // {
      //   field: `brandTypeName`,
      //   label: `资产品牌`,
      //   component: 'Render',
      //   disabled: true,
      //   placeholder: '自动带出',
      //   render: (text) => {
      //     return <span>{text ? text.split('||')[0] : '--'}</span>;
      //   },
      // },
      {
        field: `paramsInfo`,
        label: `规格型号`,
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
      },
      {
        field: `unitOfMeasurementName`,
        label: `计量单位`,
        component: 'Render',
        disabled: true,
        placeholder: '自动带出',
        render: (text) => {
          return <span>{text ? text.split('||')[0] : '--'}</span>;
        },
      },
      {
        field: `assetValue`,
        label: `资产原值`,
        component: 'InputNumber',
        placeholder: '自动带出',
        disabled: true,
        contentAfter: '元',
      },
      {
        field: `unitPrice`,
        label: `参考价值`,
        component: 'InputNumber',
        placeholder: '自动带出',
        disabled: true,
        contentAfter: '元',
      },
      {
        field: `depreciateTypeName`,
        label: `折旧方式`,
        component: 'Render',
        disabled: true,
        placeholder: '自动带出',
        render: (text) => {
          return <span>{text ? text.split('||')[0] : '--'}</span>;
        },
      },
      {
        field: `durableYears`,
        label: `使用期限`,
        component: 'InputNumber',
        placeholder: '自动带出',
        disabled: true,
        min: 0,
        contentAfter: '月',
      },
      {
        field: `useDepartmentName`,
        label: `使用部门`,
        disabled: true,
        component: 'Input',
        placeholder: '自动带出',
      },
      {
        field: `userName`,
        label: `使用人`,
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
      },
      {
        field: `locationName`,
        label: `存放区域`,
        component: 'Render',
        render: (text) => {
          return <span>{text ? text.split('||')[0] : '--'}</span>;
        },
      },
      {
        field: `locationInfo`,
        label: `详细地址`,
        component: 'Input',
        disabled: true,
        placeholder: '请输入',
      },
      {
        field: `applyFile`,
        label: `相关附件`,
        component: 'Render',
        required: false,
        placeholder: '请上传',
        render: (text, record) => {
          const fileName = 'applyFile';
          return (
            <>
              <div
                style={{
                  height: '100%',
                  display: 'flex',
                  alignItems: 'center',
                  marginLeft: '8px',
                }}
              >
                {record?.[fileName]
                  ? splitFileUrl(record?.[fileName])?.map((e, i) => {
                      return (
                        <div>
                          <Tooltip title={e.attachName} key={new Date().getTime() * 25615265152 + e?.attachName}>
                            <a
                              onClick={() => {
                                message.success('下载中，请稍后...');
                                downloadTemplate('/assetInfo/downloadFile', e?.attachName, e?.attachUrl, () => {});
                              }}
                            >
                              <MyIcon type="icon-file-text-fill" />
                              &nbsp;
                              {getFileNameNotType(e.attachName, 8)}
                            </a>
                          </Tooltip>
                          {/* 轻阅读预览 */}
                          <Tooltip title={'在线预览'}>
                            <Button type="link" size="small" onClick={() => onOpenReadOfdWord(e?.attachUrl)} icon={<EyeOutlined />} />
                          </Tooltip>
                        </div>
                      );
                    })
                  : '--'}
              </div>
            </>
          );
        },
      },
    ],
  });

  return (
    <>
      <div className="commonTabsBodyDom">
        <div className={Cls('tabsBodyInfoDom', `${styleFixCls}updateFormBox`)}>
          <ScrollBarLayout style={{ padding: '20px 10%' }}>
            <Spin spinning={false}>
              <TypographyTitle children={'材料转资产申请'} style={{ textAlign: 'center', borderLeft: 'none' }} level={1} />
              <TypographyTitle children={'基本信息'} style={{ margin: '25px 0px 20px' }} level={2} />
              <Descriptions config={config} />

              <TypographyTitle children={'材料转资产信息'} style={{ margin: '25px 0px 20px' }} level={2} />
              <Descriptions config={ReConfig} />

              <TypographyTitle children={'材料信息'} style={{ margin: '25px 0px 20px' }} level={2} />
              <UpdatePackList packList={infoObj.mAssetStuffassetList ? infoObj.mAssetStuffassetList : []} />

              <TypographyTitle children={'相关合同信息'} style={{ margin: '25px 0px 20px' }} level={2} />
              <UpdateContractList packList={infoObj.massetContractList ? infoObj.massetContractList : []} />
            </Spin>
          </ScrollBarLayout>
        </div>
      </div>
    </>
  );
};
